package xman.mstruts.dao;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.orm.ibatis.SqlMapClientTemplate;

import xman.mstruts.entity.Id;

//@Repository
@SuppressWarnings({ "rawtypes", "unchecked" })
public class GenericDAO<T extends Id> {

    @Resource
    protected SqlMapClientTemplate ibatisClientTemplate;
    
    // special return object
    public Object get(Class<T> clazz, Map params, String sqlId) {
        return ibatisClientTemplate.queryForObject(sql(clazz, sqlId), params);
    }
    
    public List<Object> list(Class<T> clazz, Map params, String sqlId) {
        return (List<Object>) ibatisClientTemplate.queryForList(sql(clazz, sqlId), params);
    }
    
    // map parameter
    public T getEntity(Class<T> clazz, Map params) {
        return (T) ibatisClientTemplate.queryForObject(sql(clazz, null), params);
    }
    
    public List<T> listEntity(Class<T> clazz, Map params) {
        return (List<T>) ibatisClientTemplate.queryForList(sql(clazz, null), params);
    }
    
    public Integer listRecord(Class<T> clazz, Map params) {
        return (Integer) ibatisClientTemplate.queryForObject(sql(clazz, null), params);
    }
    
    // T parameter
    public Integer insertReturnId(Class<T> clazz, T entity) {
        Integer id = (Integer) ibatisClientTemplate.insert(sql(clazz, null), entity);
        return id;
    }
    
    public Integer updateEntity(Class<T> clazz, T entity) {
        return ibatisClientTemplate.update(sql(clazz, null), entity);
    }
    
    public Integer deleteEntity(Class<T> clazz, T entity) {
        return ibatisClientTemplate.delete(sql(clazz, null), entity);
    }
    
    protected String sql(Class<T> clazz, String sqlId) {
        String sId = null;
        if (StringUtils.isNotEmpty(StringUtils.trimToNull(sqlId))) {
            sId = sqlId;
        } else {
            sId = new Throwable().getStackTrace()[1].getMethodName();
        }
        return clazz.getSimpleName() + "DAO." + sId;
    }
}
